package co.fitstart.weapp.api.web.controller.profile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.market.satisfaction.SatisfactionSurvey;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.agent.Agent;
import co.fitstart.entity.utils.DateFormatUtils;
import co.fitstart.weapp.api.service.CouponService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CourseScheduleService;
import co.fitstart.weapp.api.service.SatisfactionSurveyService;
import co.fitstart.weapp.api.service.StudentService;
import co.fitstart.weapp.api.service.UserAgentService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author dan
 *
 */
@RestController
@RequestMapping("/profile")
public class ProfileController {

    private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserAgentService userAgentService;
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private CouponService couponService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CourseScheduleService courseScheduleService;

    @Autowired
    private SatisfactionSurveyService satisfactionSurveyService;


    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult index(@RequestParam("unionid") String unionid) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            Agent agent = userAgentService.load(user);
            Student student = studentService.load(user);
            int courseRoundCount = 0;
            boolean vip = false;
            SatisfactionSurvey survey = null;
            List<CourseSchedule> courseSchedules = new ArrayList<>();
            
            if(student != null) {
                courseRoundCount =  courseRoundService.count(student);
                vip = studentService.isVip(student);
                survey = satisfactionSurveyService.load(student);
                courseSchedules = courseScheduleService.listCouldSignin(student);
            }
            
            httpResult.success().message("获取数据成功")
                                .data("user", user)
                                .data("agent", agent)
                                .data("student", student)
                                .data("courseRoundCount", courseRoundCount)
                                .data("vip", vip)
                                .data("survey", survey != null)
                                .data("courseSchedules", courseSchedules);
        } catch (Exception e) {
            logger.error("profile - ", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(path="/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult info(@RequestParam("unionid") String unionid) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            
            httpResult.success().message("获取数据成功")
                                .data("user", user);
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(path="/membership-card", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult membershipCard(@RequestParam("unionid") String unionid) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            
            Date effectiveEnd = userService.latestEffectiveDate(user);
            
            httpResult.success().message("获取数据成功")
                                .data("user", user)
                                .data("effectiveEnd", DateFormatUtils.format(effectiveEnd, "yyyy/MM/dd"));
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param unionid
     * @return
     */
    @RequestMapping(path = "/coupons", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult coupons(@RequestParam("unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            
            List<Coupon> coupons = couponService.listCoupon(user);
            
            List<Coupon> availableCoupons = couponService.list(user, true);
            List<Coupon> unavailableCoupons = couponService.list(user, false);
            
            httpResult.success().message("获取数据成功")
                                .data("coupons", coupons)
                                .data("availableCoupons", availableCoupons)
                                .data("unavailableCoupons", unavailableCoupons)
                                .data("userId", user.getId());
            
        } catch (Exception e) {
            logger.error("coupons - ", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 
     * @param unionid
     * @param couponId
     * @return
     */
    @RequestMapping(path = "/coupon/{couponId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult coupon(@RequestParam("unionid") String unionid,
                               @PathVariable("couponId") Long couponId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            Coupon coupon = couponService.load(couponId);
            
            if(coupon == null || !user.getId().equals(coupon.getUserId()) || !coupon.getStatus().isClaimed() || coupon.getRestDay() <= 0) {
                coupon = null;
            }
            
            String originalUserName = null;
            if(coupon.getOriginalUserId() != null) {
                User originalUser = userService.load(coupon.getOriginalUserId());
                if(originalUser != null) {
                   originalUserName = originalUser.getName() == null ? originalUser.getMobile() : originalUser.getName();
                }
            }
            
            httpResult.success().message("加载数据成功")
                                .data("originalUserName", originalUserName)
                                .data("coupon", coupon);
            
        } catch (Exception e) {
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
}
